<template>
  <div @dblclick="isEdit = true" class="w-full h-full">
    <template v-if="option.richText">
      <div v-html="content" />
      <div v-if="devMode && !content">双击编辑</div>
    </template>
    <template v-else>
      <div :style="fontStyle" :class="option.className">{{ option.text }}</div>
    </template>
  </div>
</template>
<script setup>
import { devMode, useVisual } from "@/hooks/userEditor.js"
import { isEdit, date } from "./option.js"
const attrs = useAttrs()
const option = attrs.option
const element = attrs.element
const { commonStyle } = useVisual()
const { dimension, measure } = attrs.data
let dataset = {
  dimensions: [],
  source: []
}
const content = ref("")
const init = () => {
  const settings = g.Copy(option)
  let str = settings.content
  for (const strKey in date.value) {
    str = g.replaceAll(str, `@${strKey}@`, date.value[strKey])
  }
  dataset.dimensions.forEach((item) => {
    let source = item.type === "M" ? 0 : ""
    try {
      source = dataset.source[item]
    } catch (e) {
      /* empty */
    }
    str = g.replaceAll(str, `@${item}@`, source || 0)
  })
  content.value = str
}
if (option.richText) {
  init()
}
const fontStyle = computed(() => {
  return {
    ...option,
    ...{
      fontSize: option.fontSize + "px",
      lineHeight: element.height + "px",
      fontFamily: option.fontFamily || commonStyle.value.fontFamily,
      letterSpacing: option.letterSpacing + "px"
    }
  }
})
watch([option], () => {
  init()
})
// 对外暴露的方法，接收外部传入的数据
const update = (data) => {
  dataset = {
    dimensions: [...dimension.map((i) => i.title), ...measure.map((i) => i.title)],
    source: data.data[0]
  }
  init()
}
defineExpose({
  update
})
</script>
<style scoped lang="less">
.bi-text {
  width: 100%;
  height: 100%;
}
</style>
